package com.xncoding.jwt.handler;


import com.xncoding.jwt.commons.SocketConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/***
 *  <p>
 *     用于处理用户会话相关方法
 *  </p>
 *
 * @author feilong
 * @since 2024/5/27
 */
public class SocketUsersHandler {

    /***
     * 此参数用于缓存连接用户信息
     *
     * 使用此类方式存储是用于解决实际生产环境中同一用户链接到webSocket下仍能收到消息的问题
     */
    public static final Map<String, ConcurrentHashMap<WebSocketSession, String>>
            userSessions = new ConcurrentHashMap<>();

    private static final Logger log = LoggerFactory.getLogger(SocketUsersHandler.class);

    /**
     * 添加用户
     *
     * @param session
     */
    public static void addUser(WebSocketSession session) {
        String loginUserId = extractUserIdFromSession(session);
        if (!userSessions.containsKey(loginUserId)) {
            userSessions.put(loginUserId, new ConcurrentHashMap<>());
        }
        userSessions.get(loginUserId).put(session, "ConnectedSuccess!");
    }


    /***
     * 移除用户
     * @param session
     */
    public static void removeUser(WebSocketSession session) {
        String userId = extractUserIdFromSession(session);
        if (userSessions.containsKey(userId)) {
            userSessions.get(userId).remove(session);
            if (userSessions.get(userId).isEmpty()) {
                userSessions.remove(userId);
            }
        }
    }

    /***
     * 给某个用户发送实时消息
     *
     * @param userId 链接用户id
     * @param message 消息内容
     */
    public static void sendMessageToUser(String userId, String message) {
        if (userSessions.containsKey(userId)) {
            try {
                for (WebSocketSession sess : userSessions.get(userId).keySet()) {
                    if (sess.isOpen()) {
                        sess.sendMessage(new TextMessage(message));
                    }
                }
            } catch (IOException exp) {
                log.error("send message error,please check!");
            }
        }
    }


    /***
     * 从webSocketSession会话中读取用户信息
     * @param session
     * @return
     */
    public static String extractUserIdFromSession(WebSocketSession session) {
        Map<String, Object> paramMap = session.getAttributes();
        if (paramMap != null) {
            String loginUserId = (String) paramMap.get(SocketConstants.MESSAGE_SERVICE_USER_ID_PARAM);
            return loginUserId;
        }
        return "";
    }

}
